package at.fhooe.stefanirndorfer.graphics;

import static org.lwjgl.opengl.GL11.GL_COLOR_BUFFER_BIT;
import static org.lwjgl.opengl.GL11.glClear;

import java.io.FileNotFoundException;

import org.lwjgl.LWJGLException;
import org.lwjgl.input.Keyboard;
import org.lwjgl.opengl.Display;
import org.lwjgl.opengl.DisplayMode;

import at.fhooe.stefanirndorfer.entity.Background;
import at.fhooe.stefanirndorfer.game.Game;
import at.fhooe.stefanirndorfer.input.KeyInputListener;


public class Window implements KeyInputListener{

	private static final int FRAMERATE = 60;
	private String id;
	private int width;
	private int height;
	private String title;
	private Game game;

	
		public Window(int width, int height, String title, Game game){
		id = this.getClass().getSimpleName() + System.nanoTime();
		
		this.width = width;
		this.height = height;
		this.title = title;
		this.game = game;

		setUpKeyInputListener();
	}
	
	public void openWindow() throws LWJGLException, FileNotFoundException{
		Display.setDisplayMode(new DisplayMode(width, height));
		Display.setTitle(title);
		Display.setInitialBackground(1.0f, 1.0f, 1.0f);
		Display.create();
		
		//initialisation of openGL
		Graphics_Utils.initializeOpenGL(width, height);
		
		game.getTimer().getDelta(); // call once before loop to initialise lastFrame
		int delta = 0;
		
		
		
		/** transfers the coordinates origin to the center*/
		
		while(!Display.isCloseRequested()){
			
			
			
			delta = game.getTimer().getDelta();

			//Input
			
			//process mouse input
			game.getInputManager().dispatchMouseEvents();
			
			game.getEvent_manager().update(delta);
			
			//process keyboard input
			while (Keyboard.next()){
				game.getInputManager().dispatchKeyEvents(Keyboard.getEventKey(), Keyboard.getEventKeyState());
			}
			
			//upadate Entities
			game.getEntityManager().updateAll(delta);
			
			//Render
			glClear(GL_COLOR_BUFFER_BIT);
			// if 3d
			//glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
			
			
			game.getRenderManager().renderAll();
			
			Display.setTitle("Quad-Tree-Labeling Demo");
			Display.update();
			Display.sync(FRAMERATE);
		}
		
		endProgram();
	}

	

	
	private void endProgram() {
		game.getInputManager().removeAll();
		game.getEntityManager().removeAll();
		Display.destroy();
		System.exit(0);
	}

	

	@Override
	public void setUpKeyInputListener() {
		game.getInputManager().addKeyListener(this);
		
	}

	@Override
	public void tearDownKeyInputListener(KeyInputListener il) {
		game.getInputManager().removeKeyListener(this);
		
	}

	@Override
	public void processKeyInput(int eventKey, boolean keyDown) {
		if(eventKey == Keyboard.KEY_ESCAPE && keyDown){
			endProgram();
		}
		
	}

	@Override
	public String getId() {
		return id;
	}

	public int getWindowWidth() {
		return width;
	}

	public int getWindwoHeight() {
		return height;
	}
	
}
